import {observable, action, computed, runInAction} from 'mobx'
import {Animate} from '@/lib/Animate'
import Common from '@/lib/Common'
import {StoreBase} from '@/stores'

export class ModalStore extends StoreBase {

    constructor(props) {
        super(props)
        //过渡动画名称
        this.transitionName = props.transitionName || 'zoom'
        for (var name in this.props) {
            this.props[name] = props[name]
        }
        this.animate = new Animate(this.transitionName)
        if (props.active) {
            this.show()
        }
    }

    @observable props = {
        width: null,
        height: null,
        top: null,
        left: null
    }

    @observable active = false
    /**
     * 遮罩层是否激活(因不执行动画单独设置)
     * @type {boolean}
     */
    @observable overlayerActive = false

    @action show(timeout = 200) {
        this.overlayerActive = true
        this.active = true
        //隐藏滚动条
        Common.hideScroll()
        //如果指定了触发事件元素则设置动画原定
        if (window._eventSrcElement) {
            const rect = window._eventSrcElement.getBoundingClientRect()
            let left = Common.toPx(this.props.left)
            const top = Common.toPx(this.props.top) || 200
            const width = Common.toPx(this.props.width, document.body.offsetWidth)
            if (left === 0) {
                left = document.body.offsetWidth / 2 - width / 2
            } else {
                left = left - width / 2
            }
            const offsetLeft = rect.left - left
            const offsetTop = rect.top - top + rect.height
            this.animate.setStyles({
                ...this.props,
                transformOrigin: `${offsetLeft}px ${offsetTop}px 0`
            })
        }
        this.animate.enter(timeout)
    }

    @action hide(timeout = 300) {
        this.hideAsync(timeout)
    }

    @action toggle(timeout = 300) {
        if (this.active) {
            this.hide(timeout)
        } else {
            this.show(timeout)
        }
    }

    @action hideAsync(timeout = 300) {
        this.overlayerActive = false
        return this.animate.leaveAsync(timeout).then(() => {
            runInAction(() => {
                this.active = false
            })
            Common.showScroll()
        })
    }

    @computed get styles() {
        return this.animate.styles
    }

    @computed get classNames() {
        return this.animate.classNames
    }
}
